package www.dianbaozu.com.ui.manage

import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.BaseDraggableModule
import com.chad.library.adapter.base.module.DraggableModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.loadinghelper.ViewType
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentGroupSortManagementBinding
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.data.entities.ServerGroupIncludeEntity
import www.wen.com.common.lib.data.entities.ServerGroupListEntity
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA_SYSTEM_GROUPS_COUNTS
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_SERVER_ID
import www.wen.com.common.lib.helper.loading.KeyHelper.GROUP_RESET_SORT_KEY
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY1
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import java.util.*


/**
 * @author WEN
 * @Description:频道-分组排序
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class GroupSortManagementFragment : BaseLoadingFragment<FragmentGroupSortManagementBinding>(),
        View.OnClickListener {

    /**
     * 系统分组的数量,在分组排序的时候需要加上系统分组的数量
     */
    private var mSystemGroupsCount = 1

    lateinit var mServerID: String

    private val mBaseApiViewModel: GroupSortManagementViewModel by viewModels()

    private lateinit var mSortAdapter: SortAdapter

    private var mGroups: ArrayList<ServerGroupIncludeEntity> = ArrayList()

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            tilte = getString(R.string.com_grouping_sorting),
            isShowRightText = true,
            rightText = "完成",
            action = ::titleAction
    )

    override fun getLayoutId(): Int = R.layout.fragment_group_sort_management

    @FlowPreview
    override fun actionRight() {
        mBaseApiViewModel.requestGroupSort(
                dataConversion(mSortAdapter), mServerID
        ) { groups ->
            toast("排序成功")
            val data: MutableList<ServerGroupIncludeEntity> = ArrayList()
            groups.content.forEach {
                data.add(ServerGroupIncludeEntity(1, it))
                it.channelVO.forEach { channelVO ->
                    channelVO.groupType = it.groupType
                    data.add(ServerGroupIncludeEntity(2, channelVO = channelVO))
                }
            }
            //刷新首页-服务分组
            postObject(REFRESHING_SERVER_LIST_KEY1,Object())
            //刷新频道管理的分组排序
            postObject(GROUP_RESET_SORT_KEY, ServerGroupListEntity(data))
        }
    }

    override fun lazyInitView() {
        mLoadingHelper!!.getAdapter<TitleBarUniversalAdapter>(ViewType.TITLE).mViewHolder.tvRight
        mGroups = requireArguments().getParcelableArrayList(BUNDLE_DATA)!!
        mSystemGroupsCount = requireArguments().getInt(BUNDLE_DATA_SYSTEM_GROUPS_COUNTS, 0)
        mServerID = requireArguments().getString(BUNDLE_SERVER_ID)!!


        dataBinding.rvGroupSort.layoutManager = LinearLayoutManager(requireActivity())
        dataBinding.rvGroupSort.adapter = SortAdapter(mGroups).apply {
            mSortAdapter = this
            draggableModule.isSwipeEnabled = false
            draggableModule.isDragEnabled = true
            draggableModule.isDragOnLongPressEnabled = false
            draggableModule.toggleViewId = R.id.imageView4
            draggableModule.itemTouchHelperCallback.setSwipeMoveFlags(ItemTouchHelper.START or ItemTouchHelper.END)
        }
    }

    private fun dataConversion(adapter: BaseQuickAdapter<*, *>): List<RequestBodyParameter> {
        val requestBodyParameter = mutableListOf<RequestBodyParameter>()
        var groupSort = 0
        adapter.data.forEach {
            val itemData = it as ServerGroupIncludeEntity
            val content = itemData.content
            requestBodyParameter.add(
                    RequestBodyParameter(
                            groupId = content!!.groupId,
                            groupSort = groupSort + mSystemGroupsCount
                    )
            )
            groupSort++
        }
        return requestBodyParameter
    }

    private class SortAdapter(groups: ArrayList<ServerGroupIncludeEntity>) :
            BaseQuickAdapter<ServerGroupIncludeEntity, BaseViewHolder>(
                    R.layout.item_grouping_sort_group_name,
                    groups
            ), DraggableModule {

        override fun convert(holder: BaseViewHolder, item: ServerGroupIncludeEntity) {
            val group = item.content
            holder.setText(R.id.tvCreateGroup, group!!.groupName)
        }

        override fun addDraggableModule(baseQuickAdapter: BaseQuickAdapter<*, *>): BaseDraggableModule {
            return BaseDraggableModule(baseQuickAdapter)
        }
    }

}



